const { legacy_createStore } = require("redux");

/*
  redux:
  {
    __DO_NOT_USE__ActionTypes: {
      INIT: '@@redux/INITb.m.w.r.u.h',
      REPLACE: '@@redux/REPLACE1.4.j.m.x.w',
      PROBE_UNKNOWN_ACTION: [Function: PROBE_UNKNOWN_ACTION]
    },

    applyMiddleware表示中间件，中间件主要用于做仓库的异步
    applyMiddleware: [Function: applyMiddleware],
    bindActionCreators: [Function: bindActionCreators],

    combineReducers用来做仓库的合并用的，相当于是仓库模块化
    combineReducers: [Function: combineReducers],
    compose: [Function: compose],

    createStore用来创建仓库
    createStore: [Function: createStore],

    legacy_createStore: [Function: createStore]
  }
*/

// 定义仓库数据
const initState = {
  count: 10,
  name: "tom",
};

// reducer函数需要自己定义，用来改变仓库数据的
// reducer自己需要接受两个参数
// action是一个带有type属性的对象
// reducer必须是纯函数(同步，不能改变入参，入参相同的话出参也相同)
// reducer只能return一个对象，用return的对象去替换原来的对象
const reducer = (state = initState, action) => {
  switch (action.type) {
    case "add":
      return {
        ...state,
        count: state.count + 1,
      };
    case "minus":
      return {
        ...state,
        count: state.count - action.n,
      };
    default:
      return state;
  }
};

// createStore需要传入至少一个参数reducer函数
const store = legacy_createStore(reducer);
// console.log(store);

// console.log(store.getState());
// // dispatch可以触发reducer函数，需要传递一个action对象
// store.dispatch({ type: "add" });
// console.log(store.getState());
// store.dispatch({ type: "minus", n: 2 });
// console.log(store.getState());

store.subscribe(() => {
  console.log(store.getState());
});

store.dispatch({ type: "add" });
store.dispatch({ type: "minus", n: 2 });
store.dispatch({ type: "minus", n: 3 });

/*
  store:
    {
      dispatch是用来触发reducer函数的
      dispatch: [Function: dispatch],

      subscribe订阅，当仓库的数据发生改变的时候，会自动触发
      subscribe: [Function: subscribe],

      getState函数是用来获取仓库的数据的
      getState: [Function: getState],
      replaceReducer: [Function: replaceReducer],
      '@@observable': [Function: observable]
    }
*/
